import { Context, h, Schema } from 'koishi'

export const name = 'miao-forward'

interface forwardRule{
  sourceGroupId: string;
  destGroupIdList: string[];
}

export interface Config {
  enablePrintSource: boolean;
  forwardRules: forwardRule[];
  allowedMsgSeg: string[];
}

export const Config: Schema<Config> = Schema.intersect([

  Schema.object({
    enablePrintSource: Schema.boolean()
      .default(true)
      .description("是否打印开头的群号群名"),
    forwardRules: Schema.array(
      Schema.object({
        sourceGroupId: Schema.string().description("来源群号"),
        destGroupIdList: Schema.array(Schema.string()).role('table').description("目标群号列表")
      })
    ) 
      .role('table')
      .description("转发规则"),
    allowedMsgSeg: Schema.array(String)
      .default(['at', 'text', 'face', 'img'])
      .role('table')
  }).description("基础配置")


])

export function apply(ctx: Context, config: Config) {

  ctx.command('asm_debug')
    .action(async ({ session }) => {
      await session.send(JSON.stringify( config.allowedMsgSeg ));
    })

  ctx.on('message', async ( session )=>{
    for ( const rule of config.forwardRules ){
      if ( session.guildId === rule.sourceGroupId ){
        for ( const destGroupId of rule.destGroupIdList ){

          try{
            const guildObj = await session.bot.getGuild(session.guildId);
            let msg = ``;
            if ( config.enablePrintSource )
              msg += `[来自群组： ${guildObj.name} (${session.guildId})]\n`;
            // msg += session.content;
            const elements = h.parse(session.content);
            let payload = [];
            for ( let i=0; i<elements.length; i++ ){
              const e = elements[i];
              if (config.allowedMsgSeg.includes(e.type)) 
                payload.push(e);
            }
            msg += payload.join('');
            await session.bot.sendMessage(destGroupId, msg);
          } catch(err) {
            ctx.logger.info(`[error]转发失败，源头：${session.guildId}, 目的地: ${destGroupId}. err: ${err}`);
          }

        } 
      }
    }
  })


}
